package com.sna.snaapplication.utils;

import com.sna.snaapplication.entity.usercore.Role;
import com.sna.snaapplication.entity.usercore.User;
import com.sna.snaapplication.mapper.RoleMapper;
import com.sna.snaapplication.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
@Component
public class CurrentLoginUtil {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;


    //获取当前登录用户的角色
    public boolean isAdmin() {
        Map<String, Object> map = ThreadLocalUtil.get();

        if (map == null) {
            return false;
        }
        // 从 map 中获取用户 ID，需要根据实际存储的键进行调整
        String userName = (String) map.get("username");

        if (userName == null) {
            return false;
        }
        // 根据用户 ID 查询用户信息
        User user = userMapper.findByUserName(userName);

        if (user == null) {
            return false;
        }

        Role role=roleMapper.FindByUserId(user.getUserId());

        System.out.println("当前用户的角色"+role);
        // 返回用户角色
        return role.getRoleKey().equals("admin");
    }
    //获取当前登录用户的Id
    public static Long getCurrentId(){
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return null;
        }
        Long userId = (Long) map.get("userId");
        if (userId == null) {
            return null;
        }
        return userId;
    }
    //获取当前登录用户的用户名
    public String getCurrentUserName(){
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return null;
        }
        String userName = (String) map.get("userId");
        if (userName == null) {
            return null;
        }
        return userName;
    }

}
